package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"lib/http"
	"lib/structs/tables"
	"sys/dao"
)

var RoleApi = new(roleApi)

type roleApi struct {
}

func (api roleApi) GetRole(c *gin.Context) {
	li, err := dao.RoleDB.FindAll(1)
	if err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	http.Ok(c, li)
}

func (api roleApi) Add(c *gin.Context) {
	var in tables.Role
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	self := http.GetCurrentUser(c)
	in.Creator = self.Nickname
	in.IsSys = 2
	err := dao.RoleDB.Create(in)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}

func (api roleApi) Delete(c *gin.Context) {
	in := struct {
		Id int64 `uri:"id,string" `
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	self := http.GetCurrentUser(c)
	if self.AccountLv != tables.AccountLvForRoot {
		err := fmt.Errorf("超级管理员才能删除角色")
		http.BadWithErr(c, err)
		return
	}
	err := dao.RoleDB.DeleteById(in.Id)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}
